#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Environment symulator for Wumpus game (rat).
"""

# TODO add dir of grids 
# TODO add dir of agent 
# TODO add stats

import argparse  #http://docs.python.org/dev/library/argparse.html

parser = argparse.ArgumentParser(description='Rat runs the game, Wumpus game.')
parser.add_argument('-c', type=int, dest='cycles', default=25,
                   help='maximal number of cycles to run')
parser.add_argument('--dump', '-d', action='store_true',
                   help='dumps final .idp file')
parser.add_argument('--verbose', '-v', action='count',
                   help='shows actions and percepts')
parser.add_argument('--idp3', dest='idp3', default='./bin/runidp.sh',
                   help='path to runidp script')
parser.add_argument('agent', type=argparse.FileType('r'), 
                   help='agents theory file')
parser.add_argument('cave', type=argparse.FileType('r'),
                   help='cave map file')

args = parser.parse_args()

from cave import Cave
from knight import Knight, KnightException
from nature import Nature, NatureException

c = Cave(args.cave.read())
k = Knight(args.agent.name, args.idp3)
n = Nature(c)

c = 0

try:
    percepts = n.init()
    while c < args.cycles:
        action = k.act(percepts)
        if args.verbose:
            p = ', '.join(percepts) if percepts else 'None'
            print "%d (%s) %s" % (c, p, action)
        percepts = n.react(action)
        c+=1
    raise NatureException('Timeout', args.cycles)
except (NatureException, KnightException) as e:
    if args.dump:
        fh = open('dump.idp', 'w')
        fh.write(k.genStructere())
        fh.close()
    print e[0], e[1]
